package com.eianiao.exception;

import com.eianiao.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author eianiao
 * @Date 2022 06
 * @Version 1.0
 **/
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleSQLIntegrityException(SQLIntegrityConstraintViolationException e){
        String message = e.getMessage(); // Duplicate entry 'admin' for key 'idx_username'
        //判断是否是唯一性|重复数据 错误，如果是，就开始获取到底是什么东西重复了。返回给页面
        if(message.contains("Duplicate entry")){
            String name = message.split(" ")[2];
            return R.error(name +" 已存在！");
        }
        return R.error("未知错误！");
    }

    @ExceptionHandler(CustomException.class)
    public R handleCustomException(CustomException e ){
        return R.error(e.getMessage());
    }

}
